<template>
<article :class="[{dHide: !show}, $root.platformClass.topArticle]">
  <!-- 头部 -->
  <header :class="[{dHide: showSearchList}, 'headBar', 'd-box']">
    <aside class="asideBox" @click="hidePanle">
      <a href="javascript:;" class="nextStep"><span>取消</span></a>
    </aside>
    <div class="headTitle b-flex">位置选择</div>
    <aside class="asideBox" @click="markPoint">
      <a href="javascript:;" class="nextStep"><span>确定</span></a>
    </aside>
  </header>
  <!-- 主体 -->
  <section class="">
    <div :class="{dHide: showSearchList}">
      <div class="selectLocation">
        <!-- 搜索框 -->
        <div class="searchBox">
          <div class="searchCon  d-box">
            <i class="i-search"></i>
            <input type="text" @click="showSearchPanle" v-model.trim="searchStr" placeholder="查找附近公司、写字楼" class="b-flex">
          </div>
        </div>
        <!-- 地图 -->
        <!-- 地图 -->
        <baidu-map zoom=17 :center="center"  @ready="mapHandler" :ak="$root['bmap-ak']">
          <bm-view class="mapBox" :style="mapStyle"></bm-view>
        </baidu-map>
      </div>
      <div class="attNothing" v-show="nearbyList.length === 0">
        <div class="nothingImg"></div>
        <div class="nothingTxt">{{ gpsAuthMsg || '无搜索结果'}}</div>
      </div>
      <ul class="locationList anotherPage" v-show="nearbyList.length > 0">
        <li class="frameItem" v-for="(location, index) in nearbyList" :key="index" @click="markNearby(index)">
          <div class="frameHead d-box">
            <div class="frameDepartment b-flex d-box">
              <div class="frameDepartmentName b-flex">
                <div class="locationName">{{ location.title }}</div>
                <p class="detailInfo">{{ location.address }}</p>
              </div>
              <aside>
                <i :class="[{dHide: index !== sIndex}, 'check']"></i>
              </aside>
            </div>
          </div>
        </li>
      </ul>
    </div>
    <div :class="{dHide: !showSearchList}">
      <div class="selectLocation p_fixed">
        <!-- 搜索框 -->
        <div class="searchBox d-box">
          <div class="searchCon b-flex d-box">
            <i class="i-search"></i>
            <input type="text" v-model.trim="searchStr" placeholder="查找附近公司、写字楼" class="b-flex">
          </div>
          <aside class="ta_avC" @click="cancelSearch">
            <a href="javascript:;" class="cancel">取消</a>
          </aside>
        </div>
      </div>
      <ul class="locationList">
        <li class="frameItem" v-for="(location, index) in searchResult" :key="index" @click="markSearch(index)">
          <div class="frameHead d-box">
            <div class="frameDepartment b-flex d-box">
              <div class="frameDepartmentName b-flex">
                <div class="locationName">{{ location.title }}</div>
                <p class="detailInfo">{{ location.address }}</p>
              </div>
              <aside></aside>
            </div>
          </div>
        </li>
      </ul>
    </div>
  </section>
</article>
</template>

<script>
import {BaiduMap, BmView} from 'vue-baidu-map'

export default {
  name: 'ChooseOnsitePoint',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    gpsAuthStatus: {
      type: String,
      default: 'waiting'
    },
    lng: {
      type: String,
      default: '0'
    },
    lat: {
      type: String,
      default: '0'
    }
  },
  components: {
    BaiduMap,
    BmView
  },
  data () {
    const outRange = parseInt(this.$root.myGroupInfo.range, 10)

    return {
      BMap: null,
      map: null,
      geocoder: null,
      bPoint: null, // 临时使用
      localSearch: null,
      searchStr: '',
      searchRange: outRange || 500,
      showSearchList: false,
      nearbyList: [],
      searchResult: [],
      sIndex: -1,
      sSearchIndex: -1,
      center: {lng: 113.964104, lat: 22.544448},
      marker: null,
      convertor: null,
      mapStyle: {
        width: document.body.clientWidth + 'px',
        height: '222px'
      }
    }
  },
  mounted () {

  },
  computed: {
    gpsAuthMsg () {
      const status = this.gpsAuthStatus
      const msgCfg = {
        'waiting': '正在获取GPS信息...',
        'fail': '获取GPS位置信息失败!'
      }
      return msgCfg[status]
    }
  },
  watch: {
    searchStr () {
      this.doLocalSearch()
      // this.showSearchList = this.searchStr.length > 0
    },
    gpsAuthStatus (newVal, oldVal) {
      if (newVal === 'ok') {
        // this.loadNearby('gpsAuthStatus updated')
      }
    },
    lng (newVal, oldVal) {
      if (newVal !== '0') {
        this.loadNearby('lng updated')
      }
    },
    show (newVal) {
      if (newVal) {
        this.loadNearby('show watch')
      }
    }
  },
  methods: {
    showSearchPanle () {
      this.showSearchList = !this.showSearchList
    },
    toggleSearchList () {
      this.showSearchList = !this.showSearchList
    },
    hidePanle () {
      this.sIndex = -1
      this.$emit('hidePanle')
    },
    markPoint () {
      const location = this.nearbyList[this.sIndex]
      if (this.sIndex === -1) {
        this.showTip('请选择外勤打卡地点')
        return false
      }

      this.sIndex = -1
      this.$emit('hidePanle')
      this.$emit('markPoint', {
        location: location.title,
        detailAddr: location.address,
        longitude: location.point.lng + '',
        latitude: location.point.lat + ''
      })
    },
    markSearch (index) {
      this.sSearchIndex = index
      const location = this.searchResult[this.sSearchIndex]
      try {
        const position = {
          location: location.title,
          detailAddr: location.address,
          longitude: location.point.lng + '',
          latitude: location.point.lat + ''
        }

        this.$root.setNewGroupPosition(position)
        this.$emit('hidePanle')
        this.$emit('markPoint', position)
      } catch (e) {
        console.log(e)
      }
      this.searchStr = ''
      this.searchResult = []
      this.showSearchList = !this.showSearchList
    },
    cancelSearch () {
      this.searchStr = ''
      this.searchResult = []
      this.toggleSearchList()
    },
    doLocalSearch () {
      if (this.searchStr.length > 0) {
        // 搜索定位点附近区域
        // api文档: http://lbsyun.baidu.com/cms/jsapi/class/jsapi_reference.html#a7b0
        this.localSearch.searchNearby(this.searchStr, this.bPoint, this.searchRange)
      }
    },
    localSearchHandler (result) {
      console.log('localSearchHandler')
      console.log(result)
      console.log('result.getCurrentNumPois() ', result.getCurrentNumPois())
      const lsCount = result.getCurrentNumPois()
      const tempArr = !lsCount ? [] : new Array(lsCount).fill(true)

      this.searchResult = tempArr.map((item, i) => {
        return result.getPoi(i)
      })
    },
    markNearby (index) {
      this.sIndex = index
    },
    loadNearby (tag) {
      console.log('loadNearby tag: ' + tag)
      console.log(JSON.stringify(this.$props))
      if (this.lng !== '0' && this.geocoder) {
        const point = new this.BMap.Point(+this.lng, +this.lat)
        this.bPoint = point
        // 转化gps坐标系到百度坐标系
        // 和飞信安卓、苹果平台获取的坐标数据有差别
        // http://lbsyun.baidu.com/index.php?title=webapi/guide/changeposition
        this.convertor.translate([point], this.$root.isIphone ? 1 : 3, 5, this.translateCallback)
      }
    },
    translateCallback (data) {
      const point = data.points && data.points[0] || this.bPoint
      if (data.status === 0) {
        this.marker.setPosition(point)
        this.map.centerAndZoom(point, 18)
        // 加载附近建筑物
        this.geocoder.getLocation(point, (result) => {
          console.log(result)
          this.nearbyList = result.surroundingPois
          // this.searchResult = result.surroundingPois
        }, {
          poiRadius: this.searchRange, // 半径为500米内的POI,默认100米
          numPois: 100 // 列举出50个POI,默认10个
        })
      }
    },
    mapHandler ({BMap, map}) {
      console.log(BMap, map)
      this.BMap = BMap
      this.map = map
      this.geocoder = new BMap.Geocoder()
      this.marker = new BMap.Marker(new BMap.Point(113.964104, 22.544448))
      this.convertor = new BMap.Convertor()
      // 设置偏移，处理地图容器设置为display:none后map.centerAndZoom方法 定位居中不准的问题
      map.panBy(140, 120)
      map.addOverlay(this.marker)

      // 如果已经获取到本地坐标,则直接加载附近列表
      if (this.lng !== '0') {
        this.loadNearby('baiduMapReady')
      }
      // 创建一个百度地图搜索对象
      this.localSearch = new BMap.LocalSearch(map, {onSearchComplete: this.localSearchHandler, pageCapacity: 99})
    }
  }
}
</script>
